package com.zhen.controller;

import com.alibaba.fastjson.JSON;
import com.zhen.pojo.User;
import com.zhen.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/login")
    public String login(Model model) {
//        model.addAttribute("xiaoxi", "1");
        return "login";
    }

    @RequestMapping("/loginIn")
    public String loginIn(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.queryUserByUsernameAndPassword(username, password);
        if (user == null) {
//            model.addAttribute("xiaoxi", "用户名或密码错误");
            return "login";
        }
        HttpSession session = request.getSession();
        session.setAttribute("userInfo", JSON.toJSONString(user));
        return "index";
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        session.invalidate();
        return "login";
    }

    @RequestMapping("/register")
    public String register(){
        return "register";
    }
    @RequestMapping("/registerIn")
    public String registerIn(HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        userService.addUser(username,password,name);
        return "login";
    }
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}
